Fork me on GitHub

349.TwoArrayIntesection

问题

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:

Each element in the result must be unique.
The result can be in any order.

解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet();
Set<Integer> set2 = new HashSet();
for (int i = 0; i < nums1.length; i++) {
set1.add(nums1[i]);
}

for (int j = 0; j < nums2.length; j++) {
if (set1.contains(nums2[j])) {
set2.add(nums2[j]);
}
}
int[] num = new int[set2.size()];
int i = 0;
for (Integer n : set2) {
num[i] = n;
i++;
}

return num;
}
}

本文标题:349.TwoArrayIntesection

文章作者:LiuXiaoKun

发布时间:2018年10月07日 - 23:10

最后更新:2019年02月13日 - 16:02

原始链接:https://LiuZiQiao.github.io/2018/10/07/ IntersectionofTwoArrays/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%